<template>
  <div class="course-detail">
    <el-tree
      class="tree"
      :data="nodeList"
      node-key="id"
      ref="tree"
      highlight-current
      draggable
      :props="defaultProps"
      :allow-drop="allowDrop"
      @node-drop="handleNodeDrop">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ data.sectionName || data.theme }}</span>
        <span>
          <el-button
            @click="() => editSection(data)">
            编辑
          </el-button>
          <el-button
            v-if="data.sectionName"
            type="primary"
            @click="() => addLesson(node, data)">
            添加课时
          </el-button>
          <el-button
            v-if="data.theme"
            type="success"
            @click="() => uploadVideo(node, data)">
            上传视频
          </el-button>
        </span>
      </span>
    </el-tree>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { getSectionAndLesson, saveOrUpdateSection, saveOrUpdateLesson } from '@/services/course'

export default Vue.extend({
  name: 'AllocMenu',

  props: {
    courseId: {
      type: [String, Number],
      required: true
    }
  },

  data () {
    return {
      defaultProps: {
        children: 'lessonDTOS'
      },
      nodeList: [],
      checkedKeys: []
    }
  },

  mounted () {
    this.loadNodeList()
  },

  methods: {
    loadNodeList () {
      getSectionAndLesson(this.courseId).then(res => {
        if (res.data.code === '000000') {
          this.nodeList = res.data.data
        }
      })
    },

    allowDrop (draggingNode: any, dropNode: any, type: any) {
      console.log(draggingNode, dropNode, type)
      // return false
      return type !== 'inner' && draggingNode.data.sectionId === dropNode.data.sectionId
    },

    async handleNodeDrop (draggingNode: any, dropNode: any) {
      console.log(dropNode.parent.childNodes)
      try {
        await Promise.all(
          dropNode.parent.childNodes.map((item: any, index: number) => {
            const request = item.data.lessonDTOS ? saveOrUpdateSection : saveOrUpdateLesson
            return request({
              id: item.data.id,
              orderNum: index + 1
            })
          })
        )
      } catch (err) {
        console.log(err)
      }
    },

    editSection () {
      this.$message.warning('暂不支持编辑')
    },

    addLesson () {
      this.$message.warning('暂不支持添加课时')
    },

    uploadVideo () {
      this.$message.warning('暂不支持上传视频')
    }
  }
})
</script>

<style lang="scss" scoped>
.tree {
  padding: 20px;
}
.tree ::v-deep.el-tree-node__content {
  height: auto;
  margin-bottom: 10px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
